import axios from 'axios'
import store from '@/store/index'
import { Message } from 'element-ui'
import router from '@/router/index'
import qs from 'qs'

const request = axios.create()

request.interceptors.request.use(config => {
  if (config.url.startsWith('/boss')) {
    config.baseURL = 'http://eduboss.lagou.com'
  } else {
    config.baseURL = 'http://edufront.lagou.com'
  }

  const { user } = store.state
  if (user && user.access_token) {
    config.headers.Authorization = user.access_token
  }

  return config
})

function redirctLogin () {
  router.push({
    name: 'login',
    query: {
      redirct: router.currentRoute
    }
  })
}

let isrefresh = false
let requestArr = []

request.interceptors.response.use(response => {
  return response
}, (error) => {
  if (error.response) {
    const { status } = error.response
    if (status === 400) {
      Message.error('请求参数有误')
    } else if (status === 401) {
      if (!store.state.user) {
        redirctLogin()
        return Promise.reject(error)
      }
      isrefresh = true
      return request({
        method: 'POST',
        url: '/front/user/refresh_token',
        data: qs.stringify({
          refreshtoken: store.state.user.refresh_token
        })
      }).then(res => {
        if (res.data.state !== 1) {
          redirctLogin()
          store.commit('setToken', null)
          return Promise.reject(error)
        }
        if (isrefresh) {
          requestArr.push(() => {
            request(error.config)
          })
        }
        store.commit('setToken', res.data.content)
        requestArr.forEach(item => item())
        requestArr = []

        return request(error.config)
      }).catch(err => {
        console.log(err)
      }).finally(() => {
        isrefresh = false
      })
    } else if (status === 403) {
      Message.error('没有权限，请联系管理员')
    } else if (status === 404) {
      Message.error('请求资源不存在')
    } else if (status >= 500) {
      Message.error('服务端错误，请联系管理员')
    }
  }
})

export default request
